import 'package:cloud_medicine/components/above_loading.dart';
import 'package:cloud_medicine/components/close_circle.dart';
import 'package:cloud_medicine/components/user_avatar.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/chat_api.dart';
import 'package:cloud_medicine/http/message_api.dart';
import 'package:cloud_medicine/model/base_user_info.dart';
import 'package:cloud_medicine/model/chat_detail.dart';
import 'package:cloud_medicine/package/new_bubble.dart';
import 'package:cloud_medicine/pages/add_prescription.dart';
import 'package:cloud_medicine/pages/chat_camera_select.dart';
import 'package:cloud_medicine/pages/image_show.dart';
import 'package:cloud_medicine/static/emjoy.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';

import '../components/util.dart';

class ChatDetailPage extends StatefulWidget {
  final int chatID;
  final int openPrescriptionStatus;

  ChatDetailPage({
    Key key,
    @required this.chatID,
    @required this.openPrescriptionStatus,
  }) : super(key: key);

  @override
  _ChatDetailPageState createState() => _ChatDetailPageState();
}

class _ChatDetailPageState extends State<ChatDetailPage> {
  final TextEditingController controller = TextEditingController();
  final picker = ImagePicker();
  List<String> _imageList = []; // 从图库里面选中的图片
  ChatDetail _chatDetail;
  bool isShowImages = false;
  bool isShowEmjoy;
  ScrollController _scrollController = new ScrollController();

  final InputBorder inputBorder = UnderlineInputBorder(
    borderSide: BorderSide(color: Colors.white),
    borderRadius: BorderRadius.all(
      Radius.circular(50),
    ),
  );

  @override
  void initState() {
    super.initState();
    _loadData();
    setState(() {
      isShowEmjoy = false;
    });
  }

  // 加载数据
  Future<Null> _loadData() async {
    dynamic res = await getChatDetail_api({
      'chat_id': widget.chatID,
    });
    if (res['code'] == 0) {
      if (mounted) {
        setState(() {
          _chatDetail = ChatDetail.init(res['data']);
          //   if (_scrollController.hasClients) {
          //     _scrollController
          //         .jumpTo(_scrollController.position.maxScrollExtent);
          //   }
        });
      }
    } else {
      errorToast(res['message']);
    }
  }

  // 从图库中选取图片
  Future getImageInGallery() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    if (pickedFile == null) {
      Fluttertoast.showToast(msg: '路径错误', gravity: ToastGravity.TOP);
      return;
    }
    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading(
            content: '上传中...',
          );
        });
    upLoadImage(File(pickedFile.path), (imgSrc) {
      setState(() {
        _imageList.add(imgSrc);
        isShowImages = true;
        Navigator.pop(context);
      });
    });
  }

  // 照相获取图片
  Future getImageInCamera() async {
    final pickedFile = await picker.getImage(source: ImageSource.camera);
    if (pickedFile == null) {
      Fluttertoast.showToast(
        msg: "图片路径错误",
        gravity: ToastGravity.TOP,
        backgroundColor: Colors.black,
        textColor: Colors.white,
      );
      return;
    }
    Navigator.of(context)
        .push(MaterialPageRoute(
      builder: (context) => ChatCameraPage(
        file: File(pickedFile.path),
        id: widget.chatID,
      ),
    ))
        .then((value) {
      _loadData();
    });
  }

  // 进入增加处方页面
  entryAddPrescription() {
    if (widget.openPrescriptionStatus == 0) {
      Fluttertoast.showToast(
        msg: '该聊天不能开处方',
        gravity: ToastGravity.TOP,
        backgroundColor: Colors.black,
        textColor: Colors.white,
      );
      return;
    }
    if (widget.openPrescriptionStatus == 2) {
      Fluttertoast.showToast(
        msg: user.identify.id == 2 ? '你已开处方' : '医生已开处方',
        gravity: ToastGravity.TOP,
        backgroundColor: Colors.black,
        textColor: Colors.white,
      );
      return;
    }
    if (user.identify.id == 4) {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) =>
              AddPrescriptionPage(patientID: _chatDetail.chatUser.id),
        ),
      );
      return;
    }

    openAlertDialog(context, _sendMessageToDoctor, '没有此权限，是否发送消息给医生提示其开处方');
  }

  // 非医生用户发送消息给医生
  _sendMessageToDoctor() async {
    dynamic res = await sendMessageToDoctor_api({
      'doctorID': _chatDetail.chatUser.id,
      'content': '${user.realname}请求你开处方'
    });
    res['code'] == 0 ? successToast('发送成功') : errorToast(res['message']);
  }

  _deleteImage(int index) {
    setState(() {
      _imageList.removeAt(index);
    });
  }

  _showFace() {
    setState(() {
      isShowImages = false;
      isShowEmjoy = !isShowEmjoy;
    });
  }

  _iconItem(IconData icon, int selectedNum, String type) {
    Map<String, dynamic> contrast = {
      'photo': getImageInGallery,
      'camera': getImageInCamera,
      'prescription': entryAddPrescription,
      'face': _showFace,
    };
    return Stack(
      children: <Widget>[
        GestureDetector(
          child: Icon(
            icon,
            size: 30,
            color: type == 'face' && isShowEmjoy ? Colors.blue : Colors.grey,
          ),
          onTap: () {
            contrast[type]();
          },
        ),
        selectedNum > 0
            ? Align(
                child: Container(
                  width: 15,
                  height: 15,
                  alignment: Alignment.center,
                  decoration:
                      BoxDecoration(shape: BoxShape.circle, color: Colors.blue),
                  child: Text(
                    selectedNum.toString(),
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              )
            : Container()
      ],
    );
  }

  _submitPicture(String img) async {
    dynamic res = await addChat_api(
        {"chat_id": widget.chatID, "content": img, "isFile": true});
    if (res['code'] != 0) {
      errorToast(res['message']);
    }
  }

  // 增加聊天信息
  _submit() async {
    dynamic res = await addChat_api({
      "chat_id": widget.chatID,
      "content": controller.text,
      "isFile": false
    });
    _imageList.forEach((img) {
      _submitPicture(img);
    });
    _imageList.clear();
    if (res['code'] == 0) {
      setState(() {
        controller.text = '';
      });
    } else {
      errorToast(res['message']);
    }
    await _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title:
            Text(_chatDetail == null ? '加载中' : _chatDetail.chatUser.realname),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: _chatDetail != null
                ? Container(
                    child: ListView.builder(
                        controller: _scrollController,
                        shrinkWrap: true,
                        padding: new EdgeInsets.all(5.0),
                        itemCount: _chatDetail.list.length,
                        itemBuilder: (BuildContext context, int index) {
                          bool isMy = _chatDetail.list[index].isMy;
                          bool isFile = _chatDetail.list[index].isFile;
                          return Column(
                            children: [
                              SizedBox(height: 5),
                              Row(
                                textDirection:
                                isMy ? TextDirection.rtl : TextDirection.ltr,
                                children: <Widget>[
                                  UserAvatar(
                                    userID: _chatDetail.list[index].user_id,
                                    avatar: _chatDetail.list[index].avatar,
                                    imageStyle: 50,
                                  ),
                                  Expanded(
                                    child: Bubble(
                                      color: isMy ? Colors.blue : Colors.white,
                                      direction: isMy
                                          ? BubbleDirection.right
                                          : BubbleDirection.left,
                                      child: isFile
                                          ? GestureDetector(
                                        child: Container(
                                          width: 100,
                                          height: 100,
                                          child: FadeInImage.assetNetwork(
                                            placeholder:
                                            'images/loading.gif', // 占位图
                                            image:
                                            _chatDetail.list[index].content,
                                          ),
                                        ),
                                        onTap: () {
                                          Navigator.of(context)
                                              .push(MaterialPageRoute(
                                            builder: (context) => ImageShow(
                                              url: _chatDetail
                                                  .list[index].content,
                                            ),
                                          ));
                                        },
                                      )
                                          : SelectableText(
                                          _chatDetail.list[index].content,
                                          maxLines: 3,
                                          style: TextStyle(
                                            color: isMy
                                                ? Colors.white
                                                : Colors.black,
                                          )),
                                    ),
                                  )
                                ],
                              ),
                              SizedBox(height: 5),
                            ],
                          );
                        }),
                  )
                : Container(),
          ),
          Container(
              child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Container(
                color: Colors.grey[100],
                child: Row(
                  children: <Widget>[
                    SizedBox(width: 8),
                    Expanded(
                        child: ConstrainedBox(
                      constraints: BoxConstraints(
                        maxHeight: 40,
                      ),
                      child: TextField(
                        controller: controller,
                        cursorColor: Colors.black,
                        onTap: () {
                          setState(() {
                            isShowEmjoy = false;
                            isShowImages = false;
                          });
                        },
                        decoration: InputDecoration(
                          border: inputBorder,
                          enabledBorder: inputBorder,
                          focusedBorder: inputBorder,
                          filled: true,
                          fillColor: Colors.white,
                          contentPadding: EdgeInsets.only(
                            top: 0,
                            bottom: 0,
                            left: 15,
                            right: 10,
                          ),
                        ),
                        style: new TextStyle(
                          fontSize: 16,
                          color: Colors.black,
                        ),
                      ),
                    )),
                    SizedBox(width: 20),
                    Container(
                      width: 80,
                      child: RaisedButton(
                          color: Colors.lightBlueAccent,
                          textColor: Colors.white,
                          child: Text('发送'),
                          shape: RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20))),
                          onPressed: _submit),
                    ),
                    SizedBox(width: 8),
                  ],
                ),
              ),
              Container(
                color: Colors.grey[100],
                padding: EdgeInsets.only(left: 8, right: 8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    _iconItem(Icons.photo, _imageList.length, 'photo'),
                    _iconItem(Icons.camera_alt, 0, 'camera'),
                    _iconItem(Icons.face, 0, 'face'),
                    _iconItem(Icons.note_add, 0, 'prescription'),
                    GestureDetector(
                      child: Icon(
                        Icons.remove_red_eye,
                        color: isShowImages ? Colors.blue : Colors.grey,
                      ),
                      onTap: () {
                        setState(() {
                          isShowEmjoy = false;
                          isShowImages = !isShowImages;
                        });
                      },
                    )
                  ],
                ),
              ),
              isShowImages && _imageList.length > 0
                  ? Container(
                      height: 160,
                      color: Colors.grey[100],
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 8, right: 8),
                      child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          shrinkWrap: true,
                          padding: new EdgeInsets.all(5.0),
                          itemCount: _imageList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              margin: EdgeInsets.all(8),
                              color: Colors.grey[200],
                              width: 100,
                              height: 160,
                              child: Stack(
                                children: <Widget>[
                                  Align(
                                    child: Image.network(_imageList[index]),
                                    alignment: Alignment.center,
                                  ),
                                  Align(
                                    child: CloseCircle(
                                        index: index, callback: _deleteImage),
                                    alignment: Alignment(0.9, -0.9),
                                  )
                                ],
                              ),
                            );
                          }),
                    )
                  : Container(),
              isShowEmjoy
                  ? Container(
                      height: 160,
                      color: Colors.grey[100],
                      child: GridView.custom(
                        padding: EdgeInsets.all(3),
                        shrinkWrap: true,
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 8,
                          mainAxisSpacing: 0.5,
                          crossAxisSpacing: 6.0,
                        ),
                        childrenDelegate: SliverChildBuilderDelegate(
                          (context, index) {
                            return GestureDetector(
                              onTap: () {
                                controller.text += String.fromCharCode(
                                    emjoyList[index]["unicode"]);
                              },
                              child: Center(
                                child: Text(
                                  String.fromCharCode(
                                      emjoyList[index]["unicode"]),
                                  style: TextStyle(fontSize: 20),
                                ),
                              ),
                            );
                          },
                          childCount: emjoyList.length,
                        ),
                      ),
                    )
                  : Container(),
            ],
          )),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
